<?php
namespace Home\Controller;

//通用Controller类
class PreController extends \Think\Controller{

    protected $fromuserName;//cookie名

    public function _initialize(){
        header("Content-Type:text/html;charset=utf-8");
        $this->fromuserName = C('APPID').'fromuser';
    }
    
    public function index(){
        header("Content-Type:text/html;charset=utf-8");
        $redirectUrl = I('to') == 'lists' ? 'Home/Index/lists' : 'Home/Index/index'; // 要跳转的url

        // echo $fromuser = encodeOpenid('ow6AGuAOUkUcUrjCyT2isDn9rRJc', 1477892227);die;
        if (empty($_COOKIE[$this->fromuserName])) {
            if (!$fromuser = I('fromuser')) {
                exit("<script>alert('链接参数丢失')</script>");
            } else {
                $res = decodeOpenid($fromuser);//解密出openid和时间戳

                if ($res['status'] == 0 || empty($res['openid'])) {
                    exit("<script>alert('获取用户标识失败')</script>");
                } else {
                    $member = M('WxMember')->where(array('fromuser' => $res['openid']))->find();
                    if (empty($member) || $member['timesign'] != $res['timeStamp']) {
                        exit("<script>alert('该链接已过期，请从底部菜单打开活动')</script>");
                    } else {
                        $time = time() + 3600 * 24 * 150; //半年
                        setcookie($this->fromuserName, $fromuser, $time);
                        //强制让该链接失效
                        M('WxMember')->where(array('fromuser' => $res['openid']))->save(array('timesign' => ''));
                        $this->redirect($redirectUrl);
                    }
                }
            }
        } else {
            $this->redirect($redirectUrl);
        }
    }

    // 二维码页面
    public function code() {
        $this->display();
    }

    public function clear() {
        setcookie($this->fromuserName, '', 1);
    }
    
}
